package edu.the.last.audio;

import javax.sound.midi.MidiChannel;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.Soundbank;
import javax.sound.midi.Synthesizer;

/**
 * This class is responsable for the "metronome" while recording.
 * 
 * @author albertcsani
 * 
 */
public class Tick extends Thread {
	private Synthesizer synth; // the music synthesizer
	private Soundbank soundbank; // the sound bank
	private MidiChannel[] channels; // all the channels
	private MidiChannel channel;
	private Boolean tick = true;
	private int bpm, bpb; // bpm = beat/minute; bpb = beat/bar

	// bar=utem, beat ?= negyed

	/**
	 * tries to create a synthesizer and get an instrument and channel
	 * 
	 * @param bpm
	 *            beat per minute
	 * @param bpb
	 *            beat per bar
	 */
	public Tick(int bpm, int bpb) {
		this.bpm = bpm;
		this.bpb = bpb;
		try {
			synth = MidiSystem.getSynthesizer();
			synth.open();
			soundbank = synth.getDefaultSoundbank();
			if (soundbank != null)
				synth.loadAllInstruments(soundbank);
			channels = synth.getChannels();
			channel = channels[0];
			// channel.programChange(10); //Music Box
			// channel.programChange(46); //Harp
			// channel.programChange(126); //APPLAUSE
			channel.programChange(32); // BASS
		} catch (Exception e) {
			System.out.println(e);
		}
	}

	/**
	 * Stops the ticking
	 */
	public void stopTick() {
		tick = false;
	}

	/**
	 * Method to play a note
	 * 
	 * @param note
	 *            the note to play
	 * @param duration
	 *            how long to play the note
	 */
	private void playNote(int note, int duration) {
		try {
			channel.noteOn(note, 64);

			Thread.currentThread();
			Thread.sleep(duration);
			channel.noteOff(note, 64);
		} catch (InterruptedException e) {
		}
	}

	/**
	 * tick-tack
	 */
	public void run() {
		tick = true;
		int interval = 60 * 1000 / bpm;
		while (tick) {
			playNote(50, interval);
			for (int i = 1; i < bpb && tick; i++) {
				playNote(40, interval);
			}
		}
	}
}
